package com.huadao.cart_ccs.experiment.log.paramsAnysis;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseFragment;
import com.huadao.cart_ccs.base.BasePresenter;
import com.huadao.cart_ccs.experiment.log.OnDay;
import com.huadao.cart_ccs.common.ProjectManager;
import com.huadao.cart_ccs.common.TemperatureMarkerView;
import com.huadao.cart_ccs.common.UtilHelpers;
import com.huadao.cart_ccs.data.bo.ExperimentStage;
import com.huadao.cart_ccs.greendao.GreenDaoManager;
import com.huadao.cart_ccs.greendao.gen.ExperimentStageDao;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public abstract class BaseEnvironmentFrag extends BaseFragment implements OnDay {

    @BindView(R.id.chart)
    LineChart chart;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;

//    protected LineDataSet dataSet;
    protected LineData lineData;
    private Disposable disposable;
    private ExperimentStageDao experimentStageDao;
    protected long projectId;
    protected long stageId = -1;
    private int day = 1;

    @Override
    public int getContentViewId() {
        return R.layout.frag_params_environment;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        initView();
        Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey("day")) {
            day = bundle.getInt("day");
        }
        experimentStageDao = GreenDaoManager.getInstance().getNoCacheSession().getExperimentStageDao();
        projectId = ProjectManager.getInstance().getProjectId();
        initStageId();
        initChart(chart);
        setLimitLine(chart, getLimitValue());
        lineData=new LineData();
        setLineChartData();
    }

    protected abstract void initView();

    protected abstract float getLimitValue();

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void daySelected(int day) {
        if (day != this.day) {
            if(disposable!=null) {
                disposable.dispose();
            }
            this.day=day;
            initStageId();
            setLineChartData();
        }
    }

    @Override
    public void onDestroy() {
        if(disposable!=null) {
            disposable.dispose();
        }
        super.onDestroy();
    }

    private void initChart(LineChart lineChart) {
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return UtilHelpers.getTime(value);
            }
        });
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);

        // 图表左边的y坐标轴线
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setDrawGridLines(false);

        YAxis rightAxis = lineChart.getAxisRight();
        // 不显示图表的右边y坐标轴线
        rightAxis.setEnabled(false);

        lineChart.getAxisRight().setEnabled(false);

        TemperatureMarkerView temperatureMarkerView = new TemperatureMarkerView(this.getContext(), R.layout.markerview_temperature);
        temperatureMarkerView.setChartView(lineChart);
        lineChart.setMarker(temperatureMarkerView);

        lineChart.getDescription().setText("时间");
        lineChart.setNoDataText("没有数据");
        lineChart.setScaleXEnabled(true);
        lineChart.setScaleYEnabled(false);
    }

    private void setLimitLine(LineChart lineChart, float limitValue) {
        YAxis leftAxis = lineChart.getAxisLeft();
//        leftAxis.removeAllLimitLines();

        LimitLine settingTemperatureLine = new LimitLine(limitValue, String.valueOf(limitValue));
        settingTemperatureLine.setLineWidth(2f);
        settingTemperatureLine.enableDashedLine(10f, 10f, 0f);
        settingTemperatureLine.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
        settingTemperatureLine.setTextSize(10f);
        settingTemperatureLine.setTextColor(Color.BLACK);
        settingTemperatureLine.setLineColor(getLimitLineColor());
        leftAxis.addLimitLine(settingTemperatureLine);
        leftAxis.setDrawLimitLinesBehindData(true);
        lineChart.invalidate();
    }

    protected abstract int getLimitLineColor();

    private void setLineChartData() {
        progressBar.setVisibility(View.VISIBLE);
        disposable=Observable.create(new ObservableOnSubscribe<LineData>() {
            @Override
            public void subscribe(ObservableEmitter<LineData> emitter) throws Exception {
                getData();
                emitter.onNext(lineData);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LineData>() {
                    @Override
                    public void accept(LineData lineData) throws Exception {
                        progressBar.setVisibility(View.GONE);
                        if(lineData.getEntryCount()>0) {
                            chart.setData(lineData);
//                            chart.notifyDataSetChanged();
                            chart.invalidate();
                        }else {
                            chart.clear();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    private void getData(){
        lineData.removeDataSet(0);
        LineDataSet dataSet=createLineDataSet();
        lineData.addDataSet(dataSet);
        setDataSet();
    }

    protected abstract String getLabel();

    protected abstract void setDataSet();

    private LineDataSet createLineDataSet() {
        LineDataSet set = new LineDataSet(null, getLabel());
        set.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);

        // 折线的颜色
        set.setColor(getLineColor());

        set.setCircleColor(Color.WHITE);
        set.setLineWidth(5f);
        set.setCircleRadius(2f);
        set.setFillAlpha(128);
//        set.setFillColor(R.color.temperature_line);
        set.setHighLightColor(getLineColor());
//        set.setValueTextColor(Color.WHITE);
//        set.setValueTextSize(10f);
        set.setDrawValues(false);
        return set;
    }

    protected abstract int getLineColor();

    private void initStageId() {
        ExperimentStage experimentStage = experimentStageDao.queryBuilder().where(ExperimentStageDao.Properties.ProjectId.eq(projectId), ExperimentStageDao.Properties.Day.eq(day)).unique();
        if (experimentStage!=null) {
            stageId = experimentStage.getId();
        } else {
            stageId = -1;
        }
    }

}
